import { router,addRoutes } from "~/router"
import { getToken } from "~/composables/auth"
import {
    toast,
    showFullLoading,
    hideFullLoading
} from "~/composables/util"
import store from "./store"

// 全局前置守卫
let hasGetInfo = false
router.beforeEach(async (to,from,next)=>{
    // 显示loading
    showFullLoading()

    const token = getToken()
    const role = localStorage.getItem('role') || ''

    // 没有登录，强制跳转回登录页
    if(!token && !to.path.includes('/login')){
        toast("请先登录","error")
        // 根据访问的页面判断应该跳转到哪个登录页
        if(to.path.includes('/admin')){
            return next({ path:"/admin-login" })
        } else if(to.path.includes('/repairman')){
            return next({ path:"/repairman-login" })
        } else {
            return next({ path:"/login" })
        }
    }

    // 防止重复登录
    if(token && to.path.includes('/login')){
        toast("请勿重复登录","error")
        // 根据角色跳转到对应首页
        if(role === 'admin'){
            return next({ path:"/admin-home" })
        } else if(role === 'repairman'){
            return next({ path:"/repairman-home" })
        } else {
            return next({ path:from.path ? from.path : "/" })
        }
    }

    // 检查角色权限
    if(token && role){
        // 管理员页面只能管理员访问
        if(to.path.includes('/admin') && role !== 'admin'){
            toast("没有权限访问管理员页面","error")
            return next({ path:from.path ? from.path : "/" })
        }
        // 维修工页面只能维修工访问
        if(to.path.includes('/repairman') && role !== 'repairman'){
            toast("没有权限访问维修工页面","error")
            return next({ path:from.path ? from.path : "/" })
        }
    }

    // 如果用户登录了，自动获取用户信息，并存储在vuex当中
    let hasNewRoutes = false
    if(token && !hasGetInfo){
        let { menus } = await store.dispatch("getinfo")
        hasGetInfo = true
        // 动态添加路由
        hasNewRoutes = addRoutes(menus)
    }
    hasNewRoutes ? next(to.fullPath) : next()
})

// 全局后置守卫
router.afterEach((to, from) => hideFullLoading())